import {ajax} from "@/utils/ajax.js" 
import store  from '@/store/index.js'
import { delay } from "@/utils/util";

export const TYPES = {
	ORDI:'普通',
	LUCK:'拼手气',
	BOMB:'扫雷',
}

const redAfter = async (res,options)=>{
	let {data} = res;
	if (options.requestType == 'tencent') {
		data = JSON.parse(data);
		return data;
	}else{
		if (data.retCode === '000000') {
			return data.data; 
		}	
		if (data.retCode === '12580') {
			store.dispatch('user/logout');
			uni.navigateTo({
				url: unauthPath 
			})
			throw data
		}
		console.error(data,options) 
		if (data.retDesc) {
			throw data
		} else {
			throw data
		}
	}
	return res
}


export const sendRed = async ({
	type,
	brief,
	toBizType,
	toBizId,
	totalAmount,
	totalPacket,
	preDeductId,
	targets,
	ext
})=>{
	if(sendRed.lock){
		throw new Error('正在请求中')
	}
	try{
		sendRed.lock = true
		const res = await ajax({
			url:'/redPacketInfo/send',
			data:{
				type,
				brief,
				toBizType,
				toBizId,
				totalAmount,
				totalPacket,
				preDeductId,
				targets,
				ext
			}
		})
		return res
	}finally{
		await delay(200)
		sendRed.lock = false
	}
}


export const rob = (id)=>{
	return ajax({
		url:'/redPacketInfo/rob',
		data:{
			id
		}
	},undefined,redAfter)
}

export const unpack = (id)=>{
	return ajax({
		url:'/redPacketInfo/unpack',
		data:{
			id
		}
	},undefined,redAfter)
}

export const redDetail = async (id) => {
	const {ext,...info} = await ajax({
		url:"/redPacketInfo/info",
		data:{
			id
		}
	})
	return {
		...info,
		createDate:new Date(info.createDate.split('-').join('/')).getTime(),
		...JSON.parse(ext||"{}")
	}
}

export const recList = ({id,startTime,pageSize=10}) =>{
	return ajax({
		url:"/redPacketRecord/list",
		data:{
			id,
			startTime,
			pageSize
		}
	})
}
